package com.sunmouse.toollib.widget;

import android.app.Activity;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.sunmouse.toollib.R;

/**
 * Created by Kvin on 2017/6/28.
 */
public class FootNavLayout extends LinearLayout {
    private int contentH = 0;
    private FrameLayout contentContainer;
    private TabChoice tabGroup;

    private ColorStateList txtColor;
    private float tabHeight;
    private int tabBackground;
    private int itemBackground;
    private FragmentManager manager;
    private Fragment[] fragments;
    private int lastIndex;
    private OnTabChangedListener mListener;
    private TabChoice.Mode mMode;
    private int middleIndex;//middle position


    public FootNavLayout(Context context) {
        super(context);
        initConfig(context);
    }

    public FootNavLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.FootNavLayout);
        txtColor = mTypedArray.getColorStateList(R.styleable.FootNavLayout_fnlTxtColor);
        tabHeight = mTypedArray.getDimension(R.styleable.FootNavLayout_fnlTabHeight, 90);
        tabBackground = mTypedArray.getResourceId(R.styleable.FootNavLayout_fnlTabBackground, R.color.sunmouse_white);
        itemBackground = mTypedArray.getResourceId(R.styleable.FootNavLayout_fnlItemBackground, R.color.sunmouse_transparent);
        mTypedArray.recycle();

        initConfig(context);
    }

    /**
     * initConfig some config info
     *
     * @param context
     */
    private void initConfig(Context context) {
        this.setOrientation(VERTICAL);
        //contentH = MetricsUtils.conMetrics(this).getMeasuredHeight() - navH;
        contentContainer = new FrameLayout(context);
//        contentContainer.setBackgroundResource(R.color.colorAccent);
        contentContainer.setId(getResources().getInteger(R.integer.content_id));
        LayoutParams cp = new LayoutParams(LayoutParams.MATCH_PARENT, contentH);
        cp.weight = 1;
        contentContainer.setLayoutParams(cp);
        addView(contentContainer);

        tabGroup = new TabChoice(context);
//        tabGroup.init(context, null, null, -1);
        tabGroup.setBackgroundResource(R.color.sunmouse_white);
        LayoutParams tp = new LayoutParams(LayoutParams.MATCH_PARENT, (int) tabHeight);
        tabGroup.setLayoutParams(tp);
        tabGroup.setBackgroundResource(tabBackground);
        addView(tabGroup);

        this.tabGroup.setOnCheckedChangeListener(mOnCheckedChangeListener);

        Toast.makeText(context, "" + contentContainer.getId(), Toast.LENGTH_SHORT).show();
    }

    public FootNavLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    /**
     * init content values
     */
    public void init(Activity act, Fragment[] fragments, int[] icons, String[] tabNames, int index, TabChoice.Mode mode) {
        //mode judge
        if (mode == TabChoice.Mode.NORMAL) {
            if (fragments.length != icons.length || icons.length != tabNames.length) {
                throw new RuntimeException("length is not equal");
            }
        }
        //init tab choices
        this.mMode = mode;
        this.fragments = fragments;
        this.lastIndex = index;
        this.tabGroup.init(act, tabNames, icons, txtColor, itemBackground, mode);
        this.middleIndex = fragments.length / 2;
        //add content
        if (act instanceof FragmentActivity)
            manager = ((FragmentActivity) act).getSupportFragmentManager();
        FragmentTransaction mTransaction = manager.beginTransaction();
        for (int i = 0; i < fragments.length; i++) {
            mTransaction.add(contentContainer.getId(), fragments[i])
                    .hide(fragments[i]);
        }
        mTransaction.show(fragments[index]).commit();
        ((RadioButton) this.tabGroup.getChildAt(index)).setChecked(true);
    }

    public void init(Activity act, Fragment[] fragments, int[] icons, String[] tabNames, int index) {
        this.init(act, fragments, icons, tabNames, index, TabChoice.Mode.NORMAL);
    }

    /**
     * set middle tab enable
     */
    public void setMiddleTabEnable(boolean enable) {
        int childCount = tabGroup.getChildCount();
        this.tabGroup.getChildAt(childCount / 2).setEnabled(false);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        measureChildren(widthMeasureSpec, heightMeasureSpec);//don`t forget
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }


    /**
     * on checked changed listener
     */
    private RadioGroup.OnCheckedChangeListener mOnCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            int index = group.indexOfChild(group.findViewById(checkedId));
            if (mListener != null) mListener.onTabChanged(index);
            if (mMode == TabChoice.Mode.MIDDLE) {
                if (index == middleIndex) return;
                if (index > middleIndex) index -= 1;
            }
            //set new content
            manager.beginTransaction().hide(fragments[lastIndex])
                    .show(fragments[index])
                    .commit();
            lastIndex = index;
        }
    };

    /**
     * on tab changed listener
     */
    public void setOnTabChangedListener(OnTabChangedListener mListener) {
        this.mListener = mListener;
    }
}
